<template>
  <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      label-width="120px"
      label-position="top"
      :rules="rules">
    <el-form-item label="账户类型" prop="accountType">
      <el-select-v2
          v-model="ruleForm.accountType"
          placeholder="请选择账号类型"
          :options="accountTypeOptions"
          class="w-full"
      />
    </el-form-item>
    <el-form-item label="用户名" prop="name">
      <el-input v-model="ruleForm.name" placeholder="请输入用户名"/>
    </el-form-item>
    <el-form-item label="密码" prop="pass">
      <el-input v-model="ruleForm.pass" type="password" autocomplete="off" placeholder="请输入密码" />
    </el-form-item>
    <el-form-item label="确认密码" prop="checkPass">
      <el-input
          v-model="ruleForm.checkPass"
          type="password"
          autocomplete="off"
      />
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
const ruleFormRef = ref<FormInstance>()

const accountTypeOptions = [
  { label: '企业/个人工商户', value: 'enterprise' },
  { label: '合作社', value: 'cooperative' },
  { label: '家庭农场', value: 'farm' },
  { label: '个人', value: 'personal' },
];

const ruleForm = reactive({
  accountType: undefined, // 账户类型
  name: '',
  pass: '',
  checkPass: '',
})

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== ruleForm.pass) {
    callback(new Error("两次密码不一致!"))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<typeof ruleForm>>({
  accountType: [{ required: true, message: '请选择账户类型', trigger: 'change' }],
  name: [{ required: true, message: '请输入用户名', trigger: 'change' }],
  pass: [{ required: true, validator: validatePass, trigger: 'change' }],
  checkPass: [{ required: true, validator: validatePass2, trigger: 'change' }],
})

defineExpose({
  ruleFormRef,
  ruleForm,
  rules,
})
</script>

<style lang="scss" scoped>

</style>
